<script setup lang="ts">
import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { ModelFieldsRow } from '#/views/onlineDesign/designModel/designModel.data';

import { computed, createVNode, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useVbenModal } from '@vben/common-ui';
import { AntDesignOutLined } from '@vben/icons';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { downloadFileFromUrl } from '@vben/utils';

import { useClipboard } from '@vueuse/core';
import { message, Modal } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { genConfigQueryOneApi } from '#/api/gen/config';
import { genFieldMappingQueryListApi } from '#/api/gen/fieldMapping';
import { genCodePreviewCodeApi, genCodeToProjectApi } from '#/api/gen/genCode';
import {
  genModelFieldsQueryModelFieldsApi,
  genModelFieldsSaveOrEditApi,
} from '#/api/gen/modelFields';
import { genModelClassifyQueryClassifyAndModelApi } from '#/api/gen/modelType';
import { dictQueryListApi } from '#/api/system/dict';
import { spliceUrlPrefix } from '#/utils';
import {
  ComponentList,
  RegularCodeList,
} from '#/views/onlineDesign/designModel/designModel.data';
import { fieldSelectData } from '#/views/onlineDesign/designModel/modules/modelFieldsTable.data';

interface Props {
  modelCode: string;
  loadModelFun: () => void;
}

const props = defineProps<Props>();

const router = useRouter();

const { copy } = useClipboard({ legacy: true });

const activeKey = ref('1');
const preActiveKey = ref('');
const tempBatchFields = ref();
const fieldTypeData = ref([]);
const classifyModels = ref([]);
// 当前设置配置的记录
const currentRow = ref({});
const confirmLoading = ref(false);
const previewCodeMap = ref();

const [SettingModal, settingModalApi] = useVbenModal({
  title: '模型配置',
  onConfirm: settingOnSubmit,
  closeOnClickModal: false,
});
const [BatchFieldsModal, batchFieldsModalApi] = useVbenModal({
  title: '批量增加字段',
  onConfirm: onBatchAddFields,
  closeOnClickModal: false,
});
const [PreviewCodeModal, previewCodeModalApi] = useVbenModal({
  title: '后端代码预览',
  onConfirm: () => previewCodeModalApi.close(),
  showCancelButton: false,
});

const [SettingForm, settingFormApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-3',
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-1',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldSelect',
      label: '查询',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: 'EQ',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: fieldSelectData,
      },
      fieldName: 'fieldSelectMode',
      label: '查询模式',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldSelect'],
        if(values) {
          return values?.fieldSelect === 1;
        },
      },
    },
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-3',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldRelevance',
      label: '关联',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-2',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '关联模型',
            value: 0,
          },
          {
            label: '关联树模型',
            value: 2,
          },
          {
            label: '关联字典',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldRelevanceMode',
      label: '关联模式',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRelevance'],
        if(values) {
          return values?.fieldRelevance === 1;
        },
      },
    },
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-1',
      defaultValue: 'n-1',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '1-1',
            value: '1-1',
          },
          {
            label: 'n-1',
            value: 'n-1',
          },
          {
            label: 'n-n',
            value: 'n-n',
          },
        ],
      },
      fieldName: 'fieldRelevanceModeModelRelation',
      label: '关联关系',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRelevance', 'fieldRelevanceMode'],
        if(values) {
          return (
            values?.fieldRelevance === 1 && values?.fieldRelevanceMode === 0
          );
        },
      },
    },
    {
      component: 'Select',
      fieldName: 'fieldRelevanceModeModelCode',
      formItemClass: 'col-span-3',
      label: '模型',
      dependencies: {
        triggerFields: ['fieldRelevance', 'fieldRelevanceMode'],
        if(values) {
          return (
            values?.fieldRelevance === 1 &&
            (values?.fieldRelevanceMode === 0 ||
              values?.fieldRelevanceMode === 2)
          );
        },
      },
    },
    {
      component: 'ApiSelect',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请选择显示值',
        allowClear: true,
      },
      fieldName: 'fieldRelevanceModeValKey',
      label: '显示值',
      dependencies: {
        triggerFields: [
          'fieldRelevance',
          'fieldRelevanceModeModelCode',
          'fieldRelevanceMode',
        ],
        if(values) {
          return (
            values?.fieldRelevance === 1 &&
            values?.fieldRelevanceModeModelCode &&
            (values?.fieldRelevanceMode === 0 ||
              values?.fieldRelevanceMode === 2)
          );
        },
        componentProps(values) {
          return {
            afterFetch: (data) => {
              const filteredData = data.filter((item) => item.isHandle);
              return filteredData.map((item: any) => ({
                label: `${item?.fieldAnnotation}(${item?.fieldName})`,
                value: item?.fieldName,
              }));
            },
            api: genModelFieldsQueryModelFieldsApi,
            params: {
              modelCode: values?.fieldRelevanceModeModelCode,
            },
          };
        },
      },
    },
    {
      component: 'ApiSelect',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请选择关联字段',
        allowClear: true,
      },
      fieldName: 'fieldRelevanceModeModelField',
      label: '关联字段',
      dependencies: {
        triggerFields: [
          'fieldRelevance',
          'fieldRelevanceModeModelCode',
          'fieldRelevanceMode',
        ],
        if(values) {
          return (
            values?.fieldRelevance === 1 &&
            values?.fieldRelevanceModeModelCode &&
            (values?.fieldRelevanceMode === 0 ||
              values?.fieldRelevanceMode === 2)
          );
        },
        componentProps(values) {
          return {
            afterFetch: (data) => {
              return data.map((item: any) => ({
                label: `${item?.fieldAnnotation}(${item?.fieldName})`,
                value: item?.fieldName,
              }));
            },
            api: genModelFieldsQueryModelFieldsApi,
            params: {
              modelCode: values?.fieldRelevanceModeModelCode,
            },
          };
        },
      },
    },
    {
      component: 'ApiSelect',
      formItemClass: 'col-span-3',
      componentProps: {
        afterFetch: (data) => {
          return data.map((item: any) => ({
            label: `${item?.dictName}(${item?.dictCode})`,
            value: item?.dictCode,
          }));
        },
        api: dictQueryListApi,
        placeholder: '请选择字典',
        allowClear: true,
        showSearch: true,
      },
      fieldName: 'fieldRelevanceModeValKey',
      label: '字典编码',
      dependencies: {
        triggerFields: ['fieldRelevance', 'fieldRelevanceMode'],
        if(values) {
          return (
            values?.fieldRelevance === 1 && values?.fieldRelevanceMode === 1
          );
        },
      },
    },
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-1',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldSort',
      label: '排序',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: 'desc',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '升序',
            value: 'asc',
          },
          {
            label: '降序',
            value: 'desc',
          },
        ],
      },
      fieldName: 'fieldSortMode',
      label: '排序模式',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldSort'],
        if(values) {
          return values?.fieldSort === 1;
        },
      },
    },
    {
      component: 'InputNumber',
      defaultValue: 3,
      fieldName: 'fieldSortPriority',
      label: '排序优先级',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldSort'],
        if(values) {
          return values?.fieldSort === 1;
        },
      },
    },
    {
      component: 'RadioGroup',
      formItemClass: 'col-span-3',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldRule',
      label: '校验',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '全部',
            value: 0,
          },
          {
            label: '新增',
            value: 1,
          },
          {
            label: '编辑',
            value: 2,
          },
        ],
      },
      fieldName: 'fieldRuleOpportunity',
      label: '校验时机',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRule'],
        if(values) {
          return values?.fieldRule === 1;
        },
      },
    },
    {
      component: 'RadioGroup',
      defaultValue: 1,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldRuleNotNull',
      label: '非空校验',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRule'],
        if(values) {
          return values?.fieldRule === 1;
        },
      },
    },
    {
      component: 'InputNumber',
      defaultValue: 0,
      fieldName: 'fieldRuleMin',
      label: '最小长度校验',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRule'],
        if(values) {
          return values?.fieldRule === 1;
        },
      },
    },
    {
      component: 'InputNumber',
      defaultValue: 0,
      fieldName: 'fieldRuleMax',
      label: '最大长度校验',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRule'],
        if(values) {
          return values?.fieldRule === 1;
        },
      },
    },
    {
      component: 'RadioGroup',
      defaultValue: 0,
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '否',
            value: 0,
          },
          {
            label: '是',
            value: 1,
          },
        ],
      },
      fieldName: 'fieldRuleRegular',
      label: '正则校验',
      help: '优先使用正则Code',
      rules: 'required',
      dependencies: {
        triggerFields: ['fieldRule'],
        if(values) {
          return values?.fieldRule === 1;
        },
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: RegularCodeList,
        placeholder: '请选择正则Code',
        showSearch: true,
      },
      fieldName: 'fieldRuleRegularCode',
      label: '正则Code',
      formItemClass: 'col-span-1',
      dependencies: {
        triggerFields: ['fieldRule', 'fieldRuleRegular'],
        if(values) {
          return values?.fieldRule === 1 && values?.fieldRuleRegular === 1;
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'fieldRuleRegularExpression',
      label: '正则表达式',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入正则表达式',
      },
      dependencies: {
        triggerFields: ['fieldRule', 'fieldRuleRegular'],
        if(values) {
          return values?.fieldRule === 1 && values?.fieldRuleRegular === 1;
        },
      },
    },
  ],
});

onMounted(async () => {
  fieldTypeData.value = await genFieldMappingQueryListApi({ status: 0 });
  classifyModels.value = await genModelClassifyQueryClassifyAndModelApi();
});
// 创建计算属性 options
const fieldTypeOptions = computed(() => {
  return fieldTypeData.value.map((item) => ({
    value: item.fieldType,
    label: item.remark
      ? `${item.fieldType} (${item.remark})`
      : `${item.fieldType} (${item.javaFieldType})`,
  }));
});

const gridOptions: VxeGridProps<ModelFieldsRow> = {
  height: 'auto',
  border: true,
  showOverflow: true,
  keepSource: true,
  pagerConfig: {
    // 分页
    enabled: false,
  },
  editConfig: {
    mode: 'row',
    trigger: 'click',
    showStatus: true,
    autoClear: false,
    beforeEditMethod({ row }) {
      return row.isHandle;
    },
  },
  editRules: {
    fieldName: [
      {
        required: true,
        message: '字段名称必须填写',
      },
    ],
    fieldAnnotation: [{ required: true, message: '字段注释必须填写' }],
    fieldType: [{ required: true, message: '字段类型选择' }],
    fieldLength: [{ required: true, message: '字段长度必须填写' }],
    componentName: [{ required: true, message: '组件必须选择' }],
  },
  checkboxConfig: {
    labelField: 'name',
    checkMethod: ({ row }) => {
      return row.isHandle;
    },
  },
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { title: '序号', type: 'seq', width: 50, fixed: 'left' },
    {
      editRender: { name: 'input' },
      field: 'fieldName',
      title: '字段名称',
      minWidth: 130,
      fixed: 'left',
    },
    {
      editRender: { name: 'input' },
      field: 'fieldAnnotation',
      title: '字段注释',
      minWidth: 130,
      fixed: 'left',
    },
    {
      editRender: { name: 'input' },
      field: 'fieldRemark',
      title: '字段备注',
      minWidth: 100,
    },
    {
      // editRender: { name: 'select', options: fieldTypeOptions },
      editRender: {},
      slots: { edit: 'fieldType' },
      field: 'fieldType',
      title: '字段类型',
      minWidth: 160,
    },
    {
      editRender: { name: 'input', attrs: { type: 'number' } },
      field: 'fieldLength',
      title: '字段长度',
      minWidth: 110,
    },
    {
      editRender: { name: 'input', attrs: { type: 'number' } },
      field: 'fieldDecimalPoint',
      title: '小数点',
      minWidth: 80,
    },
    {
      editRender: { name: 'input' },
      field: 'fieldDefaultVal',
      title: '默认值',
      minWidth: 80,
    },
    // {
    //   editRender: {},
    //   slots: { edit: 'fieldPrimaryKey' },
    //   field: 'fieldPrimaryKey',
    //   title: '主键',
    //   width: 80,
    // },
    {
      editRender: {},
      slots: { edit: 'fieldNotNull' },
      field: 'fieldNotNull',
      title: '非空',
      minWidth: 80,
    },
    // {
    //   editRender: {},
    //   slots: { edit: 'fieldUnique' },
    //   field: 'fieldUnique',
    //   title: '唯一',
    //   width: 80,
    // },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '模型配置',
      minWidth: 130,
    },
    {
      field: 'componentName',
      fixed: 'right',
      // editRender: { name: 'select', options: ComponentList },
      editRender: {},
      slots: { edit: 'componentName' },
      title: '组件配置',
      minWidth: 130,
    },
  ],
  proxyConfig: {
    ajax: {
      query: async () => {
        return await genModelFieldsQueryModelFieldsApi({
          modelCode: props?.modelCode ?? '',
        });
      },
    },
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
// 监听 props 的变化
watch(
  () => props.modelCode,
  async (newVal) => {
    activeKey.value = '1';
    await gridApi.query({ modelCode: newVal });
  },
);

async function addField() {
  const record: ModelFieldsRow = {
    id: '',
    fieldName: '',
    fieldAnnotation: '',
    fieldRemark: '',
    fieldType: 'varchar',
    fieldLength: 36,
    fieldDecimalPoint: 0,
    fieldDefaultVal: '',
    fieldPrimaryKey: false,
    fieldNotNull: false,
    fieldUnique: false,
    componentName: 'Input',
    // 这个是临时的
    isHandle: true,
  };
  const { row: newRow } = gridApi.grid.insertAt(record, -1);
  await gridApi.grid.setEditRow(newRow);
}
function batchAddField() {
  batchFieldsModalApi.open();
}
async function onBatchAddFields() {
  if (!tempBatchFields.value) {
    message.error('请输入内容');
    return;
  }
  const lines = tempBatchFields.value.trim().split('\n');
  const data = [];
  for (const line of lines) {
    const trimmedLine = line.trim();
    // 计算空格的数量
    const spaceCount = (trimmedLine.match(/ /g) || []).length;
    if (spaceCount === 1) {
      // 只有一个空格，按照长度为2处理
      const parts = trimmedLine.split(' ');
      if (parts.length === 2) {
        const fieldName = parts[0];
        const fieldAnnotation = parts[1];
        data.push({
          id: '',
          fieldName,
          fieldAnnotation,
          fieldRemark: '',
          fieldType: 'varchar',
          fieldLength: 36,
          fieldDecimalPoint: 0,
          fieldDefaultVal: '',
          fieldPrimaryKey: false,
          fieldNotNull: false,
          fieldUnique: false,
          // 这个是临时的
          isHandle: true,
        });
      } else {
        message.error(`${line} 格式错误,请重新输入`);
        return;
      }
    } else if (spaceCount >= 2) {
      // 包含两个或更多空格，只截取前两个部分
      const parts = trimmedLine.split(' ');
      const fieldName = parts[0];
      const fieldAnnotation = parts[1];
      // 如果需要，可以保留第三个部分作为备注
      const fieldRemark = parts.slice(2).join(' ');
      data.push({
        id: '',
        fieldName,
        fieldAnnotation,
        fieldRemark,
        fieldType: 'varchar',
        fieldLength: 36,
        fieldDecimalPoint: 0,
        fieldDefaultVal: '',
        fieldPrimaryKey: false,
        fieldNotNull: false,
        fieldUnique: false,
        // 这个是临时的
        isHandle: true,
      });
    } else {
      // 没有空格的情况
      message.error(`${line} 格式错误,请重新输入`);
      return;
    }
  }
  const { row: newRow } = gridApi.grid.insertAt(data, -1);
  await gridApi.grid.setEditRow(newRow);
  message.success(`新增 ${data.length} 条数据`);
  await batchFieldsModalApi.close();
}
async function batchDelField() {
  const checkboxRecords = gridApi.grid.getCheckboxRecords();
  if (checkboxRecords.length === 0) {
    message.warn('至少选中一行');
  } else {
    await gridApi.grid.removeCheckboxRow();
    message.success('已删除选中数据');
  }
}
function changeTabs(activeKey) {
  message.success(activeKey);
}
function openSettings(row: ModelFieldsRow) {
  currentRow.value = row;
  settingFormApi.setValues(currentRow.value);
  settingModalApi.open();
}
async function settingOnSubmit() {
  const values = await settingFormApi.getValues();
  Object.assign(currentRow.value, values);
  await settingModalApi.close();
}
async function saveOrEditFields() {
  const errMap = await gridApi.grid.validate(true);
  if (errMap) {
    message.error('模型字段校验未通过');
    return;
  }
  confirmLoading.value = true;
  try {
    const data = gridApi.grid.getData();
    const insertRecords = gridApi.grid.getInsertRecords();
    const combinedData = [...data, ...insertRecords];
    let newFormValues = {
      modelCode: props?.modelCode,
      modelFields: combinedData,
    };
    let flag = false;
    const recordset = gridApi.grid.getRecordset();
    if (
      recordset.removeRecords.length > 0 ||
      recordset.updateRecords.length > 0 ||
      recordset.insertRecords.length > 0
    ) {
      flag = true;
      newFormValues = {
        modelCode: props?.modelCode,
        modelSyncStatus: 1,
        modelFields: combinedData,
      };
    }
    const msg = await genModelFieldsSaveOrEditApi(newFormValues);
    message.success(msg);
    confirmLoading.value = false;
    if (flag) {
      await queryModel();
    }
    await gridApi.query({ modelCode: props?.modelCode });
  } catch {
    confirmLoading.value = false;
  }
}
async function queryModel() {
  if (props.loadModelFun) {
    await props.loadModelFun();
  }
}
function getSettingsBtnType(row) {
  return row.fieldSelect === 1 ||
    row.fieldRelevance === 1 ||
    row.fieldSort === 1 ||
    row.fieldRule === 1
    ? 'link'
    : 'text';
}
async function openPreviewCode() {
  const config = await loadConfig();
  if (config.packageName && config.moduleName) {
    previewCodeMap.value = await genCodePreviewCodeApi(props?.modelCode);
    preActiveKey.value = previewCodeMap.value[0]?.key;
    previewCodeModalApi.open();
  } else {
    Modal.confirm({
      title: `系统提示`,
      okText: '前往配置',
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '请先完成生成信息的配置!',
      ),
      async onOk() {
        message.success('ssss');
        await router.push({ name: 'Online/config' });
      },
      class: 'test',
    });
  }
}
async function generateCodeProject() {
  // 如果是生产环境不允许
  const env = import.meta.env.PROD ? 'prod' : 'dev';
  if (env === 'prod') {
    message.warn('生产环境下无法生成代码To项目');
    return;
  }
  const config = await loadConfig();
  if (config.packageName && config.moduleName) {
    Modal.confirm({
      title: `确认生成「${props?.modelCode}」模型代码吗?`,
      content: createVNode('div', { style: 'color:red;' }, [
        createVNode(
          'div',
          { style: 'color:red;' },
          `包名：${config.packageName}`,
        ),
        createVNode(
          'div',
          { style: 'color:red;' },
          `生成目标模块：${config.moduleName}`,
        ),
        createVNode(
          'div',
          { style: 'color:red;' },
          '如文件已存在或重名,将会替换目标文件!',
        ),
      ]),
      async onOk() {
        const msg = await genCodeToProjectApi(props?.modelCode);
        message.success(msg);
      },
      class: 'test',
    });
  } else {
    Modal.confirm({
      title: `系统提示`,
      okText: '前往配置',
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '请先完成生成信息的配置!',
      ),
      async onOk() {
        await router.push({ name: 'Online/config' });
      },
      class: 'test',
    });
  }
}
// 是否配置了代码生成必须参数
async function loadConfig() {
  return await genConfigQueryOneApi();
}
function handleFieldTypeChange(row, column) {
  // 在数组中查找匹配的 fieldType
  const matchedField = fieldTypeData.value.find(
    (item) => item.fieldType === row.fieldType,
  );
  // 如果找到匹配项，则设置 fieldLength 为对应的 defaultLength
  row.fieldLength = matchedField ? matchedField.defaultLength : 36;
  // 设置小数点
  row.fieldDecimalPoint =
    row.fieldType === 'double' || row.fieldType === 'decimal' ? 2 : 0;
  // 一下操作为了是让设置的其他值生效显示
  gridApi.grid.clearEdit(row);
  gridApi.grid.setEditRow(row, column);
}
const classifyModelsOptions = computed(() => {
  return classifyModels.value.map((item) => ({
    label: item?.name || '未命名分类',
    options: (item.models || []).map((child) => ({
      value: child.modelCode,
      label: child.modelName,
    })),
  }));
});
</script>

<template>
  <div class="h-full pl-2 pr-2">
    <PreviewCodeModal class="w-[80%]">
      <a-tabs v-model:active-key="preActiveKey" tab-position="left">
        <a-tab-pane
          v-for="item in previewCodeMap"
          :key="item?.key"
          :tab="item?.key"
        >
          <div style="overflow: auto">
            <a-button
              style="float: right"
              type="link"
              @click="copy(item?.content)"
            >
              复制
            </a-button>
            <pre v-if="item?.content">{{ item?.content }}</pre>
          </div>
        </a-tab-pane>
      </a-tabs>
    </PreviewCodeModal>
    <BatchFieldsModal class="w-[30%]">
      <template #description>
        <div>
          <p>输入格式：</p>
          <p>`字段编码*` + 空格 + `字段注释*` + 空格 + `字段其他备注`</p>
          <div class="flex flex-row pt-2">
            <div class="basis-1/4">
              <p style="color: red">例1：</p>
              <p>name 名称</p>
              <p>age 年龄</p>
            </div>
            <div class="basis-3/4">
              <p style="color: red">例2：(只需保证前两个空格断行正确)</p>
              <p>order_status 订单状态 (0待付款 1待发货 2待收货 ...)</p>
            </div>
          </div>
        </div>
      </template>
      <div>
        <a-textarea
          v-model:value="tempBatchFields"
          placeholder="请按格式输入,回车换行输入"
          :rows="16"
          allow-clear
        />
      </div>
    </BatchFieldsModal>
    <SettingModal class="w-[50%]">
      <SettingForm>
        <template #fieldRelevanceModeModelCode="slotProps">
          <a-select v-bind="slotProps" :options="classifyModelsOptions" />
        </template>
      </SettingForm>
    </SettingModal>
    <a-tabs v-model:active-key="activeKey" @change="changeTabs">
      <a-tab-pane key="1" tab="模型字段" force-render style="height: 80vh">
        <Grid v-bind="gridOptions">
          <template #toolbar-buttons>
            <a-dropdown-button class="mr-2" type="primary" @click="addField">
              新增字段
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchAddField">
                    批量加字段
                  </a-menu-item>
                </a-menu>
              </template>
              <template #icon>
                <AntDesignOutLined />
              </template>
            </a-dropdown-button>
            <a-button danger type="primary" @click="batchDelField">
              删除字段
            </a-button>
          </template>
          <template #toolbar-tools>
            <a-dropdown-button
              type="primary"
              :loading="confirmLoading"
              @click="saveOrEditFields"
            >
              保存并更新
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="openPreviewCode">
                    预览后端代码
                  </a-menu-item>
                  <a-menu-item key="2" @click="generateCodeProject">
                    后端代码生成->项目
                  </a-menu-item>
                  <a-menu-item
                    key="3"
                    @click="
                      downloadFileFromUrl({
                        source: spliceUrlPrefix(
                          `/gen/code/downloadBankCode?modelCode=${props?.modelCode}`,
                        ),
                        target: '_self',
                      })
                    "
                  >
                    后端代码下载->Zip
                  </a-menu-item>
                </a-menu>
              </template>
              <template #icon>
                <AntDesignOutLined />
              </template>
            </a-dropdown-button>
          </template>
          <template #fieldType="{ row, column }">
            <a-select
              class="w-[100%]"
              v-model:value="row.fieldType"
              @change="handleFieldTypeChange(row, column)"
            >
              <a-select-option
                v-for="(option, index) in fieldTypeOptions"
                :key="index"
                :value="option?.value"
              >
                {{ option?.label }}
              </a-select-option>
            </a-select>
          </template>
          <template #componentName="{ row }">
            <a-select class="w-[100%]" v-model:value="row.componentName">
              <a-select-option
                v-for="(option, index) in ComponentList"
                :key="index"
                :value="option?.value"
              >
                {{ option?.label }}
              </a-select-option>
            </a-select>
          </template>
          <template #fieldPrimaryKey="{ row }">
            <a-checkbox v-model:checked="row.fieldPrimaryKey" />
          </template>
          <template #fieldNotNull="{ row }">
            <a-checkbox v-model:checked="row.fieldNotNull" />
          </template>
          <template #fieldUnique="{ row }">
            <a-checkbox v-model:checked="row.fieldUnique" />
          </template>
          <template #action="{ row }">
            <a-button
              size="small"
              :type="getSettingsBtnType(row)"
              @click="openSettings(row)"
              :disabled="row.fieldName !== 'pid' && !row.isHandle"
            >
              字段配置
            </a-button>
          </template>
        </Grid>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
